package com.cpkso.buss.backend.user.service;

import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.cpkso.buss.backend.exception.EntityHasExistException;
import com.cpkso.buss.backend.exception.GivenNullParamException;
import com.cpkso.buss.backend.exception.NoSuchDataException;
import com.cpkso.buss.backend.user.dao.PermissionDao;
import com.cpkso.buss.backend.user.dao.RoleDao;
import com.cpkso.buss.backend.user.domain.Permission;
import com.cpkso.buss.backend.user.domain.Role;
import com.runze.base.web.Response;

/**
 * 角色分配service
 * 
 * 按id
 * 按用户
 * 
 * 增删改查
 * 
 * 按用户查找权限
 * 
 * @author wrzhxy@qq.com
 * @date 2018年3月18日
 */
@Service
@Transactional
public class RoleService {
	
	/**
	 * 寻找单个角色
	 * @param id
	 * @return
	 */
	public Response get(Long id) {
		return new Response(roleDao.findById(id).get());
	}
	
	/**
	 * 按用户查找
	 * @param id
	 * @return
	 */
	public Response findByUser(Long id) {
		return new Response(roleDao.findByUsersId(id));
	}
	
	/**
	 * 查找所有角色
	 * @return
	 */
	public Response findAll() {
		return new Response(roleDao.findAll());
	}
	
	/**
	 * 增加角色
	 * @param role
	 * @throws GivenNullParamException
	 * @throws EntityHasExistException
	 */
	public void create(Role role) throws GivenNullParamException, EntityHasExistException {
		if (role == null || !StringUtils.hasText(role.getName())) throw new GivenNullParamException();
		if (roleDao.findByName(role.getName()) != null) throw new EntityHasExistException();
		role.setCreateTime(new Date());
		role.setUpdateTime(null);
		roleDao.save(role);
	}
	
	/**
	 * 分配权限
	 * @param roleId
	 * @param permissionId
	 * @throws GivenNullParamException
	 * @throws NoSuchDataException
	 */
	public void grant(Long roleId, Long permissionId) throws GivenNullParamException, NoSuchDataException {
		if (roleId == null || permissionId == null) throw new GivenNullParamException();
		
		Role role = roleDao.findById(roleId).get();
		Permission permission = permissionDao.findById(permissionId).get();
		if (permission == null || role == null) throw new NoSuchDataException();
		
		role.addPermission(permission);
		role.setUpdateTime(new Date());
		roleDao.save(role);
	}
	
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private PermissionDao permissionDao;
}
